package com.chcit.mobile.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.DialogUtil;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerShipmentComponent;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.model.entity.BpartnerBean;
import com.chcit.mobile.mvp.model.entity.ReceiveBean;
import com.chcit.mobile.mvp.model.entity.ShipmentBean;
import com.chcit.mobile.mvp.ui.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.ui.adapter.ShipmentAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.di.module.ShipmentModule;
import com.chcit.mobile.mvp.contract.ShipmentContract;
import com.chcit.mobile.mvp.presenter.ShipmentPresenter;
import com.chcit.mobile.R;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
import static com.jess.arms.utils.Preconditions.checkNotNull;
public class ShipmentFragment extends ScanFragment<ShipmentPresenter> implements ShipmentContract.View {
    @BindView(R.id.et_shipment_package_document_no)
    SuperEditText etPackageNo;
    @BindView(R.id.bt_shipment_query)
    Button btQuery;
    @BindView(R.id.ckb_select_all)
    CheckBox selectAll;
    @BindView(R.id.bt_batch_confirm)
    Button btBatchConfirm;
    @BindView(R.id.linear_layout_show)
    LinearLayout mLinearLayout;
    @BindView(R.id.shipment_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_show_select)
    TextView tvShowSelect;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    ShipmentAdapter mAdapter;
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tietProductName;
    private BpartnerBean bpartnerBean;
    private String headers[] = {"选择供应商", "输入商品", "选择日期"};
    private int dateTime ;//选择的日期 0没选择  1-1月内  2-2月内  3-3月内
    private ShipmentBean shipmentBean;
    private int REQUEST_CODE = getClass().hashCode();
    public static ShipmentFragment newInstance() {
        ShipmentFragment fragment = new ShipmentFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerShipmentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .shipmentModule(new ShipmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shipment, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mCommonToolbar.setTitle("出库查询");
        mCommonToolbar.getViewByTag(1).setOnClickListener(l->{
            pop();
            l.setOnClickListener(null);
            if(getActivity() != null){
                _mActivity.finish();
            }

        });
        initDropDownMenu();

    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean("不限", ""));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<BpartnerBean>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });
        //商品选择
        final View constellationView = getLayoutInflater().inflate(R.layout.custom_layout, null);
        tietProductName = constellationView.findViewById(R.id.constellation);
        TextView ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = tietProductName.getText().toString();
                mDropDownMenu.setTabText( text.isEmpty() ? headers[1] : text);
                mDropDownMenu.closeMenu();
            }
        });

        //日期选择
        final ListView dateView = new ListView(getContext());
        List<String> dates = Arrays.asList("不限","一周内","二周内","三周内");
        final GirdDropDownAdapter<String> dateAdapter = new GirdDropDownAdapter<String>(getContext(), dates);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setSelection(1);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            dateTime = position;
            mDropDownMenu.setTabText(position == 0 ? headers[2] : dates.get(position));
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);

    }
    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        getActivity().finish();
    }

    @OnClick({R.id.bt_shipment_query, R.id.bt_batch_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_shipment_query:
                mAdapter.getData().clear();
                String pickListNo = etPackageNo.getText().toString();
                String productName = tietProductName.getText().toString();
                JSONObject data = new JSONObject();
                data.put("page", "pick");//

                data.put("orderType", "SO");
                if (!pickListNo.isEmpty()) {
                    data.put("pickListNo", pickListNo);
                }

                if (!productName.isEmpty()) {
                    data.put("productName", productName);
                }

                if(dateTime>0){
                    String dataArrivedFrom =TimeDialogUtil.getBeforeMonth(dateTime);
                    data.put("dataArrivedFrom", dataArrivedFrom);
                }
                if (!productName.isEmpty()) {
                    data.put("productName", productName);
                }
                if(bpartnerBean != null){
                    data.put("orgID",bpartnerBean.getId());
                }
                mPresenter.getData(data);
                break;
          /*  case R.id.bt_receive_date_to:
                Calendar calendarTo = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_to,calendarTo);
                break;
            case R.id.bt_receive_date_from:
                Calendar calendarFrom = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_from,calendarFrom);
                break;*/
            case R.id.bt_batch_confirm:
                doBatchConfirm();
                break;
        }
    }

    private int itemPosition  = 0;
    private void initRecyclerView() {
        mAdapter.setTitleBarView(tvShowSelect);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemPosition = position;
                shipmentBean = (ShipmentBean)adapter.getData().get(position);
                startForResult(ShipmentDetailFragment.newInstance(shipmentBean),REQUEST_CODE);
//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
            }
        });
        mRecyclerView.setAdapter(mAdapter);

    }
    /**
     * 当有数据返回时，回调
     *
     * @param requestCode 返回状态码
     * @param resultCode  是否成功状态码
     * @param data        返回数据
     */
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
            mAdapter.remove(itemPosition);
        }

    }


    @Override
    public void updateContentList(List<ShipmentBean> shipmentBeans) {
        if(shipmentBeans.size()>0){
            mAdapter.addData(shipmentBeans);
            mLinearLayout.setVisibility(View.VISIBLE);
        }else{
            mLinearLayout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public<T extends View> T getViewByTag(int i) {
        switch (i){
            case 1:
                return (T)btQuery;
            case 2:
                break;

        }
        return null;
    }
    private void doBatchConfirm() {
        final ArrayList<ShipmentBean> datas = mAdapter.getSelectedItem();
        if (datas.size() == 0) {
            DialogUtil.showMsgDialog(getContext(), "提示", "请选择至少一项");
            return;
        }
        new MaterialDialog.Builder(Objects.requireNonNull(getContext()))
                .title("提示")
                .content("确定要批量提交" + datas.size() + "个商品吗")
                .items(datas)
                // .iconRes(R.drawable.icon)
                .positiveText("确认")
                .negativeText("取消")
                //点击事件添加 方式1
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {


                            JSONArray lineData = new JSONArray();
                            for (ShipmentBean prb : datas) {
                                JSONObject params = new JSONObject();
                                params.put("pickListJobId", prb.getPickListMaId());
                                params.put("qtyConfirm", prb.getQtyLeft());
                                params.put("qtyCancel",0);
                                lineData.add(params);
                            }
                            JSONObject data = new JSONObject();
                            data.put("pickListId", shipmentBean.getPickListId());//任务
                            data.put("lineData", lineData); //拣货数量
                            data.put("isAutoShipment","N");
                            mPresenter.doBatchConfirm(data,()->{
                                for(int i: mAdapter.getSelectedItemPosition()){
                                    mAdapter.remove(i);
                                }
                                showMessage("处理成功！");
                            });
                            dialog.dismiss();
                            // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                        } else if (which == DialogAction.NEGATIVE) {
                            // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                    }
                })
                .show();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        etPackageNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if(!hidden){
            mCommonToolbar.setTitle("出库查询");
            mCommonToolbar.getViewByTag(1).setOnClickListener(l->{
                pop();
                l.setOnClickListener(null);
                if(getActivity() != null){
                    _mActivity.finish();
                }

            });
        }
        super.onHiddenChanged(hidden);

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
        selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mAdapter.checkAll();
                } else {
                    mAdapter.cancelAll();
                }
            }
        });
        etPackageNo.addTextChangedListener(textWatcher);
    }

    private TextWatcher textWatcher = new TextWatcher() {
       int mEditTextHaveInputCount = 0 ;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    btQuery.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                    btQuery.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
